<template>
  <div class="mapSurvey">
    <!--<p @click="probeOpen">新建调研点</p>-->
    <NewSurveyMap v-if="completeRefreshNewSurvey" :taskDistrict="taskDistrict" :taskRegion="taskRegion" :isSaveMapPoint="isSaveMapPoint" :taskSurveyList="taskSurveyList" @newSurveyData="newSurveyData" @mapLoading="mapLoading"></NewSurveyMap>
    <!-- 调研点弹出框 -->
    <el-dialog title="新建调研点" v-model="openProbe" append-to-body custom-class="probeDialog" width="900px">
      <p class="dialogTitle">新建调研点</p>
      <div class="probe">
        <!-- <h1>新建调研点</h1> -->
        <table>
          <tr v-if="groupId">
            <td colspan="3">
              <el-form :model="queryParamsProbe" ref="formProbe" :rules="rules" label-position="right"
                       label-width="140px" :inline="true">
                <el-form-item prop="fieldSurveyName" label="调研点名称">
                  <el-input v-model="queryParamsProbe.fieldSurveyName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="指定填写人">
                  <el-select  placeholder="请选择" v-model="selectAssignorName" value-key="value" style="width:200px">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </td>
          </tr>
          <tr v-else>
            <td colspan="3">
              <el-form :model="queryParamsProbe" ref="formProbe" :rules="rules" label-position="right"
                       label-width="140px">
                <el-form-item prop="fieldSurveyName" label="调研点名称">
                  <el-input v-model="queryParamsProbe.fieldSurveyName" placeholder="请输入" />
                </el-form-item>
              </el-form>
            </td>
          </tr>
          <tr>
            <td><span class="label">经度</span><span>{{ queryParamsProbe.longitude }}</span></td>
            <td colspan="2"><span class="label1">纬度</span><span>{{ queryParamsProbe.latitude }}</span></td>
          </tr>
          <tr>
            <td><span class="label">省</span><template v-if="queryParamsProbe.province!='' && queryParamsProbe.province.length>8"><el-tooltip effect="dark" placement="top" :content=queryParamsProbe.province><span>{{ queryParamsProbe.province.substr(0,8) }}...</span>
              {{ queryParamsProbe.province }}
            </el-tooltip></template><span v-else>{{queryParamsProbe.province}}</span>
            </td>
            <td><span class="label1">市</span><template v-if="queryParamsProbe.city!='' && queryParamsProbe.city.length>8"><el-tooltip effect="dark" placement="top" :content=queryParamsProbe.city><span>{{ queryParamsProbe.city.substr(0,8) }}...</span>
              {{ queryParamsProbe.city }}
            </el-tooltip></template><span v-else>{{queryParamsProbe.city}}</span>
            </td>
            <td><span class="label1">区（县）</span><template v-if="queryParamsProbe.area!='' && queryParamsProbe.area.length>8"><el-tooltip effect="dark" placement="top" :content=queryParamsProbe.area><span>{{ queryParamsProbe.area.substr(0,8) }}...</span>
              {{ queryParamsProbe.area }}
            </el-tooltip></template><span v-else>{{queryParamsProbe.area}}</span>
            </td>
          </tr>
          <tr>
            <!--<td colspan="3"><span class="label">所属乡镇（村）</span><span>{{ queryParamsProbe.township }}</span></td>-->
            <td colspan="3">
              <el-form :model="queryParamsProbe" ref="formProbe1" :rules="rules1" label-position="right"
                       label-width="140px">
                <el-form-item prop="township" label="所属乡镇（村）">
                  <el-input v-model="queryParamsProbe.township" placeholder="请输入" />
                </el-form-item>
              </el-form>
            </td>
          </tr>
          <tr>
            <td colspan="3"><span class="label">所属任务编号</span><span>{{ queryParamsProbe.taskCode }}</span></td>
          </tr>
        </table>
      </div>
      <template #footer>
        <el-button @click="saveProbe()" type="primary">保存</el-button>
        <el-button plain @click="closeProbe()">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="mapSurvey">
import { mapGetTaskSurveyList } from "@/api/basedatamanage/survey.js";
//地图
import NewSurveyMap from '@/map/taskmanage/sceneexamine/newSurveyMap.vue';
import { queryProvinceCityCountyNameStringByLonLat } from "@/api/earthquakeLossesEstimation/earthquakeSetting";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
import { detailTask, addSurvey } from '@/api/taskmanage/sceneExame.js'
import {  detilGroup } from "@/api/taskmanage/group.js";
const openProbe = ref(false)
const options=ref([])
const groupId = ref()
const selectAssignorName = ref({
  label:'',
  value:'',
})
const data = reactive({
  queryParamsProbe: {
    fieldSurveyName: "",
    longitude: "1551.2",
    latitude: "455.5",
    province: "河北省",
    city: "保定市",
    area: "高阳县",
    township: "某某某村",
    taskCode: "",
    createName: "",
    createId: "",
    assignorName:"",
    assignorId:"",
  },
})
const rules = {
  fieldSurveyName: [{ required: true, message: '请输入调研点名称', trigger: 'blur' }]
}
const rules1 = {
  township: [{ required: true, message: '请输入所属乡镇（村）', trigger: 'blur' }]
}
const { queryParamsProbe } = toRefs(data)

function probeOpen() {
  openProbe.value = true;
  resetProbe()
  const id = route.query.id;
  detailTask({ id: id }).then((response) => {
    groupId.value = response.data.preAssessTaskEntity.groupId
    if(groupId.value){
      getGroupName(response.data.preAssessTaskEntity.groupId)
    }
    queryParamsProbe.value.taskCode = response.data.preAssessTaskEntity.taskNum;
    queryParamsProbe.value.taskName = response.data.preAssessTaskEntity.taskName;
    queryParamsProbe.value.createName = response.data.preAssessTaskEntity.taskManager;
    queryParamsProbe.value.createId = response.data.preAssessTaskEntity.createUser;
  })
}
//取消调研
function closeProbe() {
  openProbe.value = false;
  resetProbe()
}
// 重置调研
function resetProbe() {
  queryParamsProbe.value.fieldSurveyName = ''
  selectAssignorName.value = {
    label:'',
    value:'',
  }
  proxy.resetForm("formProbe");
  queryParamsProbe.value.township = ''
  proxy.resetForm("formProbe1");
}
// 保存调研
function saveProbe() {
  proxy.$refs["formProbe"].validate((vaild) => {
    if (!vaild) {
      return;
    }
    proxy.$refs["formProbe1"].validate((vaild) => {
      if (!vaild) {
        return;
      }
      proxy.$modal.loading();
      addSurvey({...queryParamsProbe.value,assignorName:selectAssignorName.value.label,assignorId:selectAssignorName.value.value}).then((response) => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("保存成功");
        openProbe.value = false;
        //地图传参
        isSaveMapPoint.value = true;//是否已保存调研点
        //获取任务ID对应的调研点列表
        getTaskInfo();
      }).catch(err=>{proxy.$modal.closeLoading();})
    });
  });

}

//地图传参--start
const completeRefreshNewSurvey = ref(false);//防止刷新后地图不显示
const newSurveyData = (temp)=>{//新建调研点
  //根据经纬度查询行政区划省市区县信息字符串（省,市,区县）
  queryProvinceCityCountyNameStringByLonLat({lon:temp.geometry.flatCoordinates[0],lat:temp.geometry.flatCoordinates[1]}).then((response) => {
    nextTick(() => {
      console.log("地址解析");
      console.log(response.data);
      let pronvinceCityCountyName = response.data;//省,市,区县,乡镇
      if(pronvinceCityCountyName===""){
        proxy.$modal.msgError("校验失败！经纬度未查到省市区县信息.");
        return;
      }
      let array = pronvinceCityCountyName.split(",");
      //显示
      openProbe.value = true;
      resetProbe();
      const id = route.query.id;
      queryParamsProbe.value.longitude = temp.longitude;
      queryParamsProbe.value.latitude = temp.latitude;
      queryParamsProbe.value.province = temp.province;
      /*queryParamsProbe.value.city = temp.city;
      queryParamsProbe.value.area = temp.area;
      queryParamsProbe.value.township = temp.township;*/
      if(array.length>0){
        queryParamsProbe.value.province = array[0];
      }
      if(array.length>1){
        queryParamsProbe.value.city = array[1];
      }
      if(array.length>2){
        queryParamsProbe.value.area = array[2];
      }
      if(array.length>3){
        queryParamsProbe.value.township = array[3];
      }
      console.log("新建调研点");
      console.log(temp);
      isSaveMapPoint.value = false;
      detailTask({ id: id }).then((response) => {
        groupId.value = response.data.preAssessTaskEntity.groupId
        if(groupId.value){
          getGroupName(response.data.preAssessTaskEntity.groupId)
        }
        console.log(response.data.preAssessTaskEntity);
        queryParamsProbe.value.taskCode = response.data.preAssessTaskEntity.taskNum;
        queryParamsProbe.value.taskName = response.data.preAssessTaskEntity.taskName;
        queryParamsProbe.value.createName = response.data.preAssessTaskEntity.taskManager;
        queryParamsProbe.value.createId = response.data.preAssessTaskEntity.createUser;
      })
    });
  });
}
const mapLoading = (msg)=>{//地图查询loading
  if(msg!=null){
    proxy.$modal.loading(msg);
  }else{
    proxy.$modal.closeLoading();
  }
}
//任务ID对应的调研点列表
const taskSurveyList = ref([]);
//获取任务ID对应的调研点列表
function getTaskSurveyList(taskCode){
  console.log("获取任务taskCode对应的调研点列表"+taskCode);
  //获取任务ID对应的调研点列表
  mapGetTaskSurveyList(taskCode).then(response => {
    nextTick(() => {
      taskSurveyList.value = response.data;
      console.log("查询任务taskCode对应的抽样点调查列表");
      console.log(taskSurveyList.value);
      completeRefreshNewSurvey.value = true;//防止地图刷新后不显示
    });
  });
}
//获取任务区域信息
const taskDistrict = ref("");
const taskRegion = ref("");
function getTaskInfo(){
  const id = route.query.id;
  detailTask({ id: id }).then((response) => {
    console.log(response.data.preAssessTaskEntity);
    console.log("test");
    taskDistrict.value = response.data.preAssessTaskEntity.taskDistrict;
    taskRegion.value = response.data.preAssessTaskEntity.taskRegion;
    console.log(taskDistrict.value);
    console.log(taskRegion.value);
    let taskCode = response.data.preAssessTaskEntity.taskNum;
    //获取任务taskCode对应的调研点列表
    getTaskSurveyList(taskCode);
  });
}
getTaskInfo();
//是否已保存调研点
const isSaveMapPoint = ref(false);
//地图传参--end


// 获取小组信息
function getGroupName(groupId){
  detilGroup({ groupId: groupId }).then((response) => {
    console.log(response.data,'小组信息');
    const memberlist = response.data.memberlist.map(item => {
      return Object.assign({},{"label":item.realName,"value":item.uuid})
    });
    const expertlist = response.data.expertlist.map(item => {
      return Object.assign({},{"label":item.realName,"value":item.uuid})
    });
    const groupLeader= [{
      label:response.data.fwGroupEntity.groupLeader,
      value: response.data.fwGroupEntity.groupLeaderId,
    }]
    options.value = [...groupLeader,...memberlist,...expertlist]
  });
}

</script>

<style lang='scss' scoped>
.probe {
  margin: 0 auto;
  width: 750px;
  display: flex;
  flex-direction: column;
  justify-content: center;

  h1 {
    text-align: center;
    font-weight: 700;
    font-size: 24px;
    color: rgb(16, 124, 229);
  }

  .label {
    text-align: right;
    display: inline-block;
    color: #606266;
    font-weight: 700;
    height: 32px;
    width: 142px;
    padding-right: 14px;
  }

  .label1 {
    text-align: right;
    display: inline-block;
    color: #606266;
    font-weight: 700;
    height: 32px;
    width: 90px;
    padding-right: 14px;
  }
}
</style>